<template>
  <div>
    <el-select style="width: 98%;" @change="handleZdChange" v-model="currZd" value-key="zdmc">
      <el-option v-for="zd in zdList" :key="zd.zdmc" :value="zd" :label="zd.zdzwmc"/>
    </el-select>
    <el-input v-model="search"/>
    <my-tree ref="myTree" :filter-node-method="filterNode" :data="clList" :props="props" @item-click="handleItemClick"/>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import MyTree from "@/components/MyTree";

let reg = /[A-Za-z_]+\.[A-Za-z_]+/g

function getZdmcList(bds) {
  if (!bds) return []
  let arr = bds.match(reg)
  if (!arr) return []
  return arr.map(item => item)
}

export default {
  components: {MyTree},
  name: "SelectCl",
  props: {
    bds: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currZd: {},
      zdList: [],

      clList: [],
      props: {
        id: "dm",
        label: 'mc',
      },
      search: ''
    }
  },
  computed: {
    ...mapState(['stTreeObj'])
  },
  async mounted() {
    let zdmcList = getZdmcList(this.bds)
    let zdList = []
    for (let zdmc of zdmcList) {
      if (zdList.find(item => item.zdmc === zdmc)) continue;
      let stjg = this.stTreeObj[zdmc]
      if (!stjg || !stjg.sjybm) continue;
      zdList.push(stjg)
    }
    if (zdList.length) {
      this.currZd = zdList[0]
      this.handleZdChange()
    }
    this.zdList = zdList;
  },
  watch: {
    search() {
      this.$refs.myTree.filter(this.search)
    }
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data[this.props.label].indexOf(value) !== -1;
    },
    async handleZdChange() {
      let res = await this.$api.getSjysj({
        sjydz: this.currZd.sjydz,
        glcs: this.currZd.glcs
      })
      this.clList = this.$listToTree(res, 'dm', 'fdm');
    },
    handleItemClick(ff) {
      // console.log(ff)
      // let tree = this.$refs.tree
      // let nodes = tree.getCheckedNodes()
      // nodes = JSON.parse(JSON.stringify(nodes)).map(item => {
      //   delete item.children
      //   return item
      // })
      this.$emit('select', ff)
    }
  }
}
</script>

<style scoped>

</style>
